import { openDB } from 'idb';

class DB {
    constructor() {
      this.dbName = 'workflowDB'
      this.storeName = 'applications'
      this.version = 1
    }
  
    // 打开或创建数据库
    async open() {
      try {
        return await openDB(this.dbName, this.version, {
          upgrade(db) {
            if (!db.objectStoreNames.contains('applications')) {
              db.createObjectStore('applications', { keyPath: 'id' });
            }
          },
        });
      } catch (error) {
        console.error('打开数据库失败:', error);
        throw error;
      }
    }
  
    // 保存全部应用数据
    async saveAll(data) {
      try {
        const db = await this.open();
        const tx = db.transaction(this.storeName, 'readwrite');
        const store = tx.objectStore(this.storeName);
        await store.put({ id: 1, data: JSON.parse(JSON.stringify(data)) });
        await tx.done;
      } catch (error) {
        console.error('保存数据失败:', error);
        throw error;
      }
    }
  
    // 加载全部应用数据
    async loadAll() {
      try {
        const db = await this.open();
        const tx = db.transaction(this.storeName, 'readonly');
        const store = tx.objectStore(this.storeName);
        const result = await store.get(1);
        return result?.data || [];
      } catch (error) {
        console.error('加载数据失败:', error);
        throw error;
      }
    }
  }
  
  // 导出 DB 的实例而不是类
  export const db = new DB()
  